<template>
  <div class="ai-bill-container">
    <div class="welcome-message">
      欢 迎 使 用 A I 智 能 体 - 爱 小 记
    </div>
    <h2 style="text-align: center;">- - - 主要功能:通过用户的收支描述，对账单数据进行记录和处理 - - -</h2>
    <div class="tips">
      <p>💡 提示：</p>
      <ul>
        <li>您可以通过语音或文本输入来记录您的收支情况,也可以指示我来帮您处理账单。</li>
        <li>输入完成后，点击“发送”按钮，系统将自动处理并记录您的账单。</li>
      </ul>
    </div>

    <div class="qa-box">
      <div v-for="(item, index) in questionsAndAnswers" :key="index" class="qa-item">
        <div class="question"><strong>问题:</strong> {{ item.question }}</div>
        <div class="answer"><strong>回答:</strong> {{ item.answer }}</div>
      </div>
    </div>

    <div class="input-box">
      <div class="robot-icon" style="font-size: 30px;">
        🤖
      </div>
      <input v-model="inputText" placeholder="请输入您对小记的指示" ref="input" />
      <button @click="toggleSpeechRecognition" :disabled="isListening">
        <span v-if="!isListening">语音输入</span>
        <span v-else class="loading">正在聆听...</span>
      </button>
      <button @click="sendRequest" :disabled="isLoading">
        <span v-if="!isLoading">发送</span>
        <span v-else class="loading">发送中...</span>
      </button>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'AiRecord',
  data() {
    return {
      inputText: '',
      response: '',
      isLoading: false,
      isListening: false,
      questionsAndAnswers: []
    };
  },
  created() {
    console.log('AiRecord 组件创建');
    console.log('this.$annyang:', this.$annyang);
    if (this.$annyang) {
      console.warn('annyang 插件未正确初始化');
    }
  },
  beforeDestroy() {
    if (this.$annyang && this.$annyang.isListening()) {
      this.$annyang.abort();
    }
  },
  methods: {
    async sendRequest() {
      this.isLoading = true;
      const currentQuestion = this.inputText; // 保存当前问题
      try {
        const res = await axios.post('http://localhost:8888/ai-bill/operation', null, {
          params: {
            input: currentQuestion
          }
        });
        this.response = res.data;
      } catch (error) {
        console.error('请求失败:', error);
        this.response = '请求失败，请稍后重试';
      } finally {
        this.questionsAndAnswers.unshift({ question: currentQuestion, answer: this.response }); // 将问题与回答加入列表
        this.inputText = ''; // 清空输入框
        this.isLoading = false;
      }
    },
    startAnnyangSpeechRecognition() {
      if (!this.$annyang) {
        alert('当前浏览器不支持语音识别功能');
        return;
      }

      this.isListening = true;

      const commands = {
        '*text': (text) => {
          console.log('识别到语音内容:', text);
          this.inputText = text;
        }
      };

      this.$annyang.addCommands(commands);
      this.$annyang.start({ language: 'zh-CN' });

      this.annyangStopHandler = () => {
        this.isListening = false;
        console.log('语音识别已结束');
      };

      this.$annyang.addCallback('end', this.annyangStopHandler);
      
      this.$annyang.addCallback('error', (err) => {
        console.error('语音识别出错:', err);
        if (err.error === 'network') {
          alert('网络异常：无法连接到语音识别服务，请检查网络后重试。');
        }
      });
      
      this.$annyang.addCallback('resultNoMatch', (unmatchedPhrases) => {
        console.warn('未匹配的语音内容:', unmatchedPhrases);
      });
    },
    stopOfflineRecognition() {
      if (this.$annyang && this.$annyang.isListening()) {
        this.$annyang.abort();
      }
      this.isListening = false;
    },
    toggleSpeechRecognition() {
      if (this.$annyang && this.$annyang.isListening()) {
        this.stopOfflineRecognition();
        return;
      }

      this.startAnnyangSpeechRecognition();
    }
  }
};
</script>

<style>
.ai-bill-container {
  display: flex;
  flex-direction: column;
  height: auto;
  margin-top: 30px;
}

.welcome-message {
  text-align: center;
  font-size: 35px;
  font-weight: bold;
  margin-bottom: 60px;
  color: #409eff;
  height: 20px;
}

.tips {
  background-color: #f0f9eb;
  padding: 15px;
  border-radius: 8px;
  margin: 20px auto;
  width: 80%;
  max-width: 800px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  margin-bottom: -110px;
}

.tips p {
  font-weight: bold;
  color: #67c23a;
  margin-bottom: 10px;
}

.tips ul {
  list-style-type: disc;
  padding-left: 20px;
}

.tips li {
  margin-bottom: 5px;
  color: #606266;
}

.response-box {
  flex: 1;
  display: flex;
  align-items: flex-end;
  padding: 20px;
  min-height: 200px;
  max-height: 300px;
  margin-top: 50px;
}

.white-container {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 800px;
  margin: 0 auto;
}

.input-box {
  display: flex;
  justify-content: center;
  padding: 20px;
  margin-top: 50px;
  gap: 10px;
}

.input-box input {
  width: 40%;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  margin-right: 10px;
}

.input-box button {
  padding: 5px 20px;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 10px;
  cursor: pointer;
}

.input-box button:disabled {
  background-color: #a0cfff;
  cursor: not-allowed;
}

.loading {
  display: inline-block;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

.robot-icon {
  font-size: 24px;
  margin-right: 10px;
  animation: bounce 2s infinite;
}

@keyframes bounce {

  0%,
  100% {
    transform: translateY(0);
  }

  50% {
    transform: translateY(-10px);
  }
}

.qa-box {
  padding: 20px;
  margin-top: 20px;
}

.qa-item {
  background-color: #f9f9f9;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 10px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.question {
  color: #333;
  font-weight: bold;
  margin-bottom: 10px;
}

.answer {
  color: #555;
}
</style>